<template>
  <div v-if="!isShowDetails" class="priceSourcing">
    <div class="myFixed">
      <PageTitle :goBack="true" title="商品详情" />
      <div class="myCardCss" style="margin-bottom: 0px;font-weight: 600;font-size: 20px;border-bottom: 1px solid #dcdfe6;white-space: nowrap;overflow: auto">
        {{ goodsName }}
      </div>
    </div>
    <div class="myCardCss" style="padding-top: 120px">
      <div class="detail-div__filter-container">
        <!-- <a-spin :spinning="state.areaLoading">
          <a-tree-select
            class="detail-a-select__filter"
            v-model:value="chartFilter.area"
            :tree-data="state.areaList"
            :treeDefaultExpandedKeys="['0']"
            placeholder="地区选择"
            @change="chartFilterChange"
          >
            <template #title="{ label }">{{ label }}</template>
          </a-tree-select>
        </a-spin> -->
        <a-select
          class="detail-a-select__filter"
          v-model:value="chartFilter.date"
          placeholder="均价日期范围"
          style="margin-right: 0px"
        >
          <a-select-option
            v-for="item of dateList"
            :key="`date_filter${item.id}`"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </div>
      <div class="detail-div__chart-container">
        <div class="detail-div__chart-gradient">
          <a-spin :spinning="state.priceLoading">
            <div class="detail-div__chart-gradient-main">
              <div class="detail-div__chart-half-year">
                <span class="detail-span__half-year-title">{{ chartHalfYearName }}</span>
                <span class="detail-span__half-year-content">{{ chartHalfYearDate }}</span>
              </div>
              <div class="detail-div__chart-transaction-price">
                <span v-if="!chartHalfYearObject" class="detail-span__transaction-price-title"
                  >暂无历史均价信息</span
                >
                <span v-else class="detail-span__transaction-price-title"
                  >平均成交价（元/
                  {{ state.goodsPriceDetail ? state.goodsPriceDetail.unit : '' }}
                  )
                </span>
                <span class="detail-span__transaction-price-content">{{ chartHalfYearPrice }}</span>
              </div>
            </div>
          </a-spin>
        </div>

        <div class="detail-div__chart-line-container">
          <div class="detail-div__chart-line-filter">
            <div class="detail-div__chart-line-filter-button">
              <span
                class="detail-span__filter-button"
                :class="{
                  'detail-span__filter-button-active':
                    chartHistoryFilter.date === 'weekPriceHistory',
                }"
                @click="setChartHistoryFilter('date', 'weekPriceHistory')"
                >周价格曲线</span
              >
              <span
                class="detail-span__filter-button"
                :class="{
                  'detail-span__filter-button-active':
                    chartHistoryFilter.date === 'monthPriceHistory',
                }"
                @click="setChartHistoryFilter('date', 'monthPriceHistory')"
                >月价格曲线</span
              >
            </div>
            <div class="detail-div__chart-line-filter-price">
              <img
                class="detail-img__filter-price"
                :class="{ 'detail-img__filter-price-active': historyState }"
                src="./../../../assets/images/productDetail_chart1.png"
                @click="toogleHistoryGetState"
              />
              <a-spin :spinning="state.historyFuturePriceLoading">
                <div style="height: 32px; display: flex; align-items: center">
                  <img
                    class="detail-img__filter-price"
                    :class="{ 'detail-img__filter-price-active': futureState }"
                    src="./../../../assets/images/productDetail_chart2.png"
                    @click="toogleGetFutureState"
                  />
                </div>
              </a-spin>
              <!-- @click="getGoodsFuturePrice" -->
            </div>
          </div>
          <a-spin :spinning="state.historyPriceLoading">
            <div ref="chartLineRef" class="detail-div__chart-line"></div>
          </a-spin>
        </div>
      </div>
    </div>
    <div class="myCardCss">
      <!-- <div class="detail-div__filter-container">
        <a-spin :spinning="state.areaLoading">
          <a-tree-select
            class="detail-a-select__filter"
            v-model:value="resultFilter.area"
            :tree-data="state.areaList"
            :treeDefaultExpandedKeys="['0']"
            placeholder="地区选择"
            @change="resultFilterChange"
          >
            <template #title="{ label }">{{ label }}</template>
          </a-tree-select>
        </a-spin>
      </div> -->
      <div class="detail-div__table-container">
        <a-spin :spinning="state.resultLoading">
          <a-table
            class="detail-a-table__main"
            :dataSource="resultTable.dataSource"
            :columns="resultTable.columns"
            :pagination="{
              ...resultFilter,
              showTotal: (total) => `共${total}条`,
              showSizeChanger: false,
            }"
            @change="tableChange"
            :scroll="{ y: 600 }"
          >
            <template #key="{ index }">
              <span>{{ (resultFilter.current - 1) * resultFilter.pageSize + index + 1 }}</span>
            </template>
            <template #companyName="{ record }">
              <a-spin :spinning="record.loading" style="overflow: hidden">
                <span @click="openDetails(record)" class="detail-span__table-link">{{
                  record.companyName
                }}</span>
              </a-spin>
            </template>
          </a-table>
        </a-spin>
      </div>
    </div>
  </div>

  <SupplierDetails v-if="isShowDetails" :company-id="companyId" @go-back="goBack" />
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, readonly } from 'vue';
  import { useRoute } from 'vue-router';
  import * as echarts from 'echarts';
  import axios from 'axios';
  import { cloneDeep } from 'lodash-es';

  import PageTitle from '/@/components/PageTitle/index.vue';
  import SupplierDetails from '/@/components/SupplierDetails/index.vue';

  import {
    getAreaTree,
    getGoodsPriceDetail,
    getGoodsHistoryPriceDetail,
    getGoodsFuturePriceMonthDetail,
    getGoodsFuturePriceWeekDetail,
    getSuppliers,
  } from '/@/api/sourcingBigData/index';

  // const page = reactive({
  //   loading: false,
  // });

  const route = useRoute();
  const goodsName = ref(localStorage.getItem('goodsName'))
  const myChart: any = ref(null);
  const companyId = ref('');
  const chartLineRef = ref(null);
  const historyState = ref(true);
  const futureState = ref(false);
  const xDataLast = ref([]);

  const isShowDetails = ref(false);

  const chartHalfYearName = computed(() => {
    let areaName = '';

    const dp = (list) => {
      list.forEach((item) => {
        if (item.id === chartFilter.area) {
          areaName = item.name;
          return;
        } else if (Array.isArray(item.children) && item.children.length > 0) {
          dp(item.children);
        }
      });
    };
    dp(state.areaList);

    const dataName = dateList.find((item) => item.id === chartFilter.date);

    return `${areaName}${dataName?.name}`;
  });

  const chartHalfYearObject = computed(() => {
    if (!state.goodsPriceDetail) {
      return null;
    }

    const priceInfo = state.goodsPriceDetail.priceInfo.find(
      (item) => item.type.toString() === chartFilter.date.toString(),
    );
    if (!priceInfo) {
      return null;
    }

    return priceInfo;
  });

  const chartHalfYearDate = computed(() => {
    if (!state.goodsPriceDetail) {
      return '';
    }

    const priceInfo = state.goodsPriceDetail.priceInfo.find(
      (item) => item.type.toString() === chartFilter.date.toString(),
    );
    if (!priceInfo) {
      return '';
    }

    const { timeRange } = priceInfo;

    return `${timeRange[0]} 至 ${timeRange[1]}`;
  });

  const chartHalfYearPrice = computed(() => {
    if (!state.goodsPriceDetail) {
      return '';
    }

    const priceInfo = state.goodsPriceDetail.priceInfo.find(
      (item) => item.type.toString() === chartFilter.date.toString(),
    );
    if (!priceInfo) {
      return '';
    }

    return priceInfo.price;
  });

  const dateList = readonly([
    {
      id: 1,
      name: '前一个月',
    },
    {
      id: 2,
      name: '前三个月',
    },
    {
      id: 3,
      name: '近半年',
    },
    {
      id: 4,
      name: '近一年',
    },
    {
      id: 5,
      name: '上周 ',
    },
  ]);

  const state: any = reactive({
    areaLoading: false,
    priceLoading: false,
    historyPriceLoading: false,
    historyFuturePriceLoading: false,
    resultLoading: false,

    areaList: [],

    goodsPriceDetail: null,

    goodsPriceHistoryDetail: null,

    goodsPriceFutureMonthList: [],
    goodsPriceFutureWeekList: [],
  });

  const chartFilter = reactive({
    area: '0',
    date: 3,
  });

  const chartHistoryFilter = reactive({
    date: 'monthPriceHistory',
  });

  const setChartHistoryFilter = (prop, value) => {
    chartHistoryFilter[prop] = value;
    futureState.value = false;
    initChart();
  };

  const resultFilter = reactive({
    area: '0',
    current: 1,
    pageSize: 20,
    total: 0,
  });

  const resultTable = reactive({
    dataSource: [],
    columns: [
      {
        title: '序号',
        dataIndex: 'key',
        key: 'key',
        align: 'left',
        slots: { customRender: 'key' },
        width: 80,
      },
      {
        title: '企业名称',
        dataIndex: 'companyName',
        key: 'companyName',
        align: 'left',
        slots: { customRender: 'companyName' },
      },
      {
        title: '代表人',
        dataIndex: 'legalPerson',
        key: 'legalPerson',
        align: 'left',
        width: 100,
      },
      {
        title: '注册资本',
        dataIndex: 'registeredCapital',
        key: 'registeredCapital',
        align: 'left',
      },
      {
        title: '成立日期',
        dataIndex: 'regDateTime',
        key: 'regDateTime',
        align: 'left',
        width: 150,
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
        align: 'left',
        width: 150,
      },
      {
        title: '地址',
        dataIndex: 'companyAddress',
        key: 'companyAddress',
        align: 'left',
      },
    ],
  });

  // const goBack = () => {
  //   console.log(231312);
  // };

  const chartFilterChange = () => {
    getGoodsPrice();
  };

  // const resultFilterChange = () => {
  //   getGoodsSuppliers();
  // };

  const initChart = () => {
    if (!state.goodsPriceHistoryDetail) {
      return;
    }

    if (myChart.value) {
      myChart.value.dispose();
    }

    const data: any = state.goodsPriceHistoryDetail[chartHistoryFilter.date];

    let xDataOrigin = data.map((item) => {
      if (chartHistoryFilter.date === 'monthPriceHistory') {
        return item.monthDate;
      } else {
        return item.weekDate;
      }
    });
    let yDataOrigin = data.map((item) => item.price);

    let xData = [];
    let yData: number[] = [];
    let itemStyle = {};

    if (historyState.value) {
      xData = xData.concat(xDataOrigin);
      yData = yData.concat(yDataOrigin);
    }

    if (futureState.value) {
      if (chartHistoryFilter.date === 'monthPriceHistory') {
        xData = xData.concat(state.goodsPriceFutureMonthList.map((item) => item.monthDate));
        yData = yData.concat(state.goodsPriceFutureMonthList.map((item) => item.price));
      } else {
        xData = xData.concat(state.goodsPriceFutureWeekList.map((item) => item.weekDate));
        yData = yData.concat(state.goodsPriceFutureWeekList.map((item) => item.price));
      }
    }

    if (!historyState.value && !futureState.value) {
      xData = cloneDeep(xDataLast.value);
    }

    const chart = echarts.init(chartLineRef.value);
    myChart.value = chart;

    let visualMap: any = undefined;
    if (historyState.value && futureState.value) {
      visualMap = {
        show: false,
        dimension: 0,
        pieces: [
          {
            lte: yDataOrigin.length - 2,
            color: '#C11A20',
          },
          {
            lte: yDataOrigin.length - 1,
            color: '#C11A20',
          },
          {
            gt: yDataOrigin.length - 1,
            color: '#1473DC',
          },
        ],
      };
    } else if (historyState.value && !futureState.value) {
      itemStyle = {
        color: '#C11A20',
      };
    } else if (!historyState.value && futureState.value) {
      itemStyle = {
        color: '#1473DC',
      };
    }

    const option: any = {
      grid: {
        left: '5%',
        right: '5%',
        bottom: '0%',
        top: '10%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xData,
        axisTick: {
          show: false,
        },
      },
      yAxis: {
        type: 'value',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: (params) => {
          const obj: any = params[0];
          if (!obj) {
            return '';
          }

          let isFuture = false;
          if (chartHistoryFilter.date === 'monthPriceHistory') {
            const goods = state.goodsPriceFutureMonthList.find(
              (item) => item.monthDate === obj.axisValue,
            );
            if (goods) {
              isFuture = true;
            }
          } else {
            const goods = state.goodsPriceFutureWeekList.find(
              (item) => item.weekDate === obj.axisValue,
            );
            if (goods) {
              isFuture = true;
            }
          }

          return `
            <div style='width: 134px; border-radius: 4px;'>
              <span style="display:block; font-size: 14px; font-weight: 500; line-height: 22px; color: #303133; margin-bottom: 10px;">${
                obj.axisValue
              }</span>
              ${
                isFuture
                  ? `<div style="display: flex; align-items: center; font-weight: normal; line-height: 22px;">
                      <span style="display: block; width: 10px; height: 10px; background: #1473DC; border-radius: 50%; margin-right: 4px;"></span>
                      预测价格
                      <span style="display: inline-block; font-weight: 500; line-height: 22px; color: #303133; margin-left: 4px;">${obj.value}</span>
                    </div>`
                  : `<div style="display: flex; align-items: center; font-weight: normal; line-height: 22px;">
                      <span style="display: block; width: 10px; height: 10px; background: #C11A20; border-radius: 50%; margin-right: 4px;"></span>
                      当前均价
                      <span style="display: inline-block; font-weight: 500; line-height: 22px; color: #303133; margin-left: 4px;">${obj.value}</span>
                    </div>`
              }
            </div>
          `;
        },
      },
      visualMap: visualMap,
      series: [
        {
          name: '当前均价',
          type: 'line',
          stack: 'Total',
          data: yData,
          itemStyle: itemStyle,
        },
      ],
    };

    xDataLast.value = cloneDeep(xData);

    chart.setOption(option);
  };

  const getArea = () => {
    state.areaLoading = true;
    getAreaTree()
      .then((data) => {
        const dg = (list) => {
          list.forEach((item) => {
            item.label = item.name;
            item.value = item.id;

            if (Array.isArray(item.children) && item.children.length > 0) {
              dg(item.children);
            }
          });
        };
        dg(data);

        state.areaList = [data[0]];
      })
      .finally(() => {
        state.areaLoading = false;
      });
  };

  const getGoodsPrice = () => {
    state.priceLoading = true;
    getGoodsPriceDetail({
      goodsCode: route.params.goodsCode,
      areaCode: chartFilter.area,
      typeInteger: chartFilter.date,
    })
      .then((data) => {
        state.goodsPriceDetail = data;
      })
      .finally(() => {
        state.priceLoading = false;
      });
  };

  const getGoodsHistoryPrice = () => {
    state.historyPriceLoading = true;
    getGoodsHistoryPriceDetail({
      goodsCode: route.params.goodsCode,
    })
      .then((data) => {
        state.goodsPriceHistoryDetail = data;
        initChart();
      })
      .finally(() => {
        state.historyPriceLoading = false;
      });
  };

  const toogleHistoryGetState = () => {
    historyState.value = !historyState.value;
    initChart();
  };

  const toogleGetFutureState = () => {
    futureState.value = !futureState.value;
    getGoodsFuturePrice();
  };

  const getGoodsFuturePrice = () => {
    if (
      chartHistoryFilter.date === 'weekPriceHistory' &&
      state.goodsPriceFutureWeekList.length === 0
    ) {
      state.historyFuturePriceLoading = true;
      getGoodsFuturePriceWeekDetail({
        goodsCode: route.params.goodsCode,
      })
        .then((data) => {
          state.goodsPriceFutureWeekList = data;
          initChart();
        })
        .finally(() => {
          state.historyFuturePriceLoading = false;
        });
    } else if (
      chartHistoryFilter.date === 'monthPriceHistory' &&
      state.goodsPriceFutureMonthList.length === 0
    ) {
      state.historyFuturePriceLoading = true;
      getGoodsFuturePriceMonthDetail({
        goodsCode: route.params.goodsCode,
      })
        .then((data) => {
          state.goodsPriceFutureMonthList = data;
          initChart();
        })
        .finally(() => {
          state.historyFuturePriceLoading = false;
        });
    } else {
      initChart();
    }
  };

  const getGoodsSuppliers = () => {
    state.resultLoading = true;
    getSuppliers({
      goodsCode: route.params.goodsCode,
      areaCode: resultFilter.area,
      limit: resultFilter.current,
      pageSize: resultFilter.pageSize,
    })
      .then((data) => {
        resultTable.dataSource = data.list.map((item) => {
          item.loading = false;
          return item;
        });
        resultFilter.total = data.total;
      })
      .finally(() => {
        state.resultLoading = false;
      });
  };

  const tableChange = (e) => {
    resultFilter.current = e.current;
    getGoodsSuppliers();
  };

  const openDetails = (row) => {
    row.loading = true;
    axios({
      url: 'https://openapi.jiansheku.com/jsk/company/getIdByKey',
      method: 'get',
      params: {
        key: row.companyName,
      },
    })
      .then(({ data }) => {
        if (data.code == 200) {
          companyId.value = data.data.cid.toString();
          isShowDetails.value = true;
        }
      })
      .finally(() => {
        row.loading = false;
      });
  };

  const goBack = () => {
    isShowDetails.value = false;
    getGoodsHistoryPrice();
  };

  const init = () => {
    if (!route.params.goodsCode) {
      throw new Error('商品详情页必须要有参数id');
    }

    // getArea();
    getGoodsPrice();
    getGoodsHistoryPrice();
    getGoodsSuppliers();
  };
  init();
</script>

<style scoped lang="less">
  .myCardCss {
    width: 100%;
    margin-bottom: 8px;
    padding: 16px;
    padding-top: 12px;

    &:last-child {
      margin-bottom: 0px;
    }

    .detail-div__filter-container {
      display: flex;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0px;
      }

      .detail-a-select__filter {
        width: 144px;
        margin-right: 8px;
      }
    }

    .detail-div__table-container {
      width: 100%;

      .detail-span__table-link {
        color: #1473dc;
        font-size: 14px;
        font-weight: normal;
        line-height: 23px;
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }

      :deep(.detail-a-table__main) {
        .ant-table-thead {
          .ant-table-cell {
            padding-left: 16px;
            padding-right: 16px;
          }
        }
      }
    }

    .detail-div__chart-container {
      display: flex;
    }

    .detail-div__chart-gradient {
      width: 296px;
      height: 260px;
      margin-right: 20px;
      background: linear-gradient(180deg, rgba(249, 233, 233, 0.4) 0%, #f9e9e9 100%);

      .detail-div__chart-gradient-main {
        width: 296px;
        height: 260px;
        display: flex;
        justify-content: center;
        flex-flow: column;

        .detail-div__chart-half-year {
          margin-bottom: 24px;

          .detail-span__half-year-title {
            display: block;
            color: #c11a20;
            font-size: 18px;
            font-weight: 500;
            line-height: 26px;
            text-align: center;
            margin-bottom: 4px;
          }

          .detail-span__half-year-content {
            display: block;
            font-size: 14px;
            font-weight: normal;
            line-height: 22px;
            color: #909399;
            text-align: center;
          }
        }

        .detail-div__chart-transaction-price {
          .detail-span__transaction-price-title {
            display: block;
            font-size: 16px;
            font-weight: normal;
            line-height: 24px;
            color: #606266;
            text-align: center;
            margin-bottom: 12px;
          }

          .detail-span__transaction-price-content {
            display: block;
            font-size: 36px;
            font-weight: bold;
            line-height: 28px;
            color: #c11a20;
            text-align: center;
          }
        }
      }
    }

    .detail-div__chart-line-container {
      width: 100%;

      .detail-div__chart-line-filter {
        display: flex;
        justify-content: space-between;

        .detail-div__chart-line-filter-button {
          display: flex;

          .detail-span__filter-button {
            width: 100px;
            height: 32px;
            line-height: 30px;
            display: block;
            box-sizing: border-box;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            color: #303133;
            font-size: 12px;
            font-weight: normal;
            text-align: center;
            cursor: pointer;

            &:first-child {
              border-right: none;
              border-top-right-radius: 0px;
              border-bottom-right-radius: 0px;
            }

            &:last-child {
              border-top-left-radius: 0px;
              border-bottom-left-radius: 0px;
            }

            &.detail-span__filter-button-active {
              color: #c11a20;
            }
          }
        }

        .detail-div__chart-line-filter-price {
          display: flex;
          align-items: center;
          height: 32px;
          border-radius: 4px;
          background: #fafafa;
          padding: 0px 12px;

          .detail-img__filter-price {
            display: block;
            height: 20px;
            cursor: pointer;
            margin-right: 20px;
            opacity: 0.3;

            &.detail-img__filter-price-active {
              opacity: 1;
            }

            &:last-child {
              margin-right: 0px;
            }
          }
        }
      }

      .detail-div__chart-line {
        flex: 1;
        height: 228px;
      }
    }
  }

  :deep(.ant-pagination-item-link) {
    border: none;
  }
  .myFixed {
    position: fixed;
    z-index: 10;
    width: calc(100% - 258px);
    background: #ffffff;
  }
</style>
